// 计算总分的函数
function calculateTotalScore() {
    var questionCount = parseInt($('#questionCount').val());  // 获取题数
    var questionValue = parseInt($('#questionValue').val());  // 获取每题分值

    // 校验题数和分值的合法性
    if (isNaN(questionCount) || questionCount < 1) {
        alert('题数必须大于0！');
        return;
    }
    if (isNaN(questionValue) || questionValue < 1) {
        alert('每题分值必须大于0！');
        return;
    }

    // 计算总分
    var totalScore = questionCount * questionValue;

    // 更新总分输入框的值
    $('#examTotalScore').val(totalScore);
}
$(document).ready(function() {
    loadExams();  // 页面加载时加载试卷列表
    calculateTotalScore();  // 初始加载时计算总分

    // 启动和停止试卷按钮的状态设置
    function updateExamButtonStatus(exams) {
        exams.forEach(function(exam) {
            var startExamButton = $('#startExamBtn_' + exam.id);
            var stopExamButton = $('#stopExamBtn_' + exam.id);

            // 启动按钮的状态
            if (exam.status === '已启动') {
                startExamButton.prop('disabled', true); // 启动按钮禁用
                stopExamButton.prop('disabled', false); // 停止按钮启用
            } else {
                startExamButton.prop('disabled', false); // 启动按钮启用
                stopExamButton.prop('disabled', true); // 停止按钮禁用
            }
        });
    }

    // 加载试卷列表并更新按钮状态
    // 修改加载试卷列表的部分
    function loadExams() {
        $.ajax({
            url: '/teacher/getExams',  // 获取所有试卷的接口
            type: 'GET',
            success: function(response) {
                var tableBody = $("#examTable tbody");
                tableBody.empty();

                if(response.code === 200 && response.data.length > 0) {
                    response.data.forEach(function(exam) {
                        var row = `<tr>
                            <td>${exam.examId}</td>
                            <td>${exam.title}</td>
                            <td>${exam.questionCount}</td>
                            <td>${exam.scorePerQuestion}</td>
                            <td>${exam.createdAt}</td>
                            <td>${exam.status === 'active' ? '已启动' : '已停止'}</td>
                            <td>
                                <button class="btn btn-info btn-sm viewExam" data-id="${exam.examId}">查看</button>
                                <button class="btn btn-warning btn-sm editExam" data-id="${exam.examId}">编辑</button>
                                <button class="btn btn-danger btn-sm deleteExam" data-id="${exam.examId}">删除</button>
                                <button class="btn btn-primary btn-sm viewStudentScores" data-id="${exam.examId}">查看学生成绩</button>
                                ${exam.status === 'active' ?
                                                    `<button class="btn btn-success btn-sm stopExam" data-id="${exam.examId}" id="stopExamBtn_${exam.examId}">停止试卷</button>` :
                                                    `<button class="btn btn-success btn-sm startExam" data-id="${exam.examId}" id="startExamBtn_${exam.examId}">启动试卷</button>`
                                                }
                            </td>
                        </tr>`;


                        tableBody.append(row);
                    });
                    updateExamButtonStatus(response.data);  // 更新按钮的状态
                }
            },
            error: function() {
                alert("加载试卷失败！");
            }
        });
    }

    // 查看学生成绩的操作
    $(document).on("click", ".viewStudentScores", function() {
        var examId = $(this).data("id");
        $.ajax({
            url: '/teacher/getStudentScores?id=' + examId,  // 请求获取学生成绩的接口
            type: 'GET',
            success: function(response) {
                if (response.code === 200) {
                    var records = response.data;

                    // 清空成绩列表
                    var studentList = $('#studentScoreList');
                    studentList.empty();

                    if (records.length > 0) {
                        records.forEach(function(record, index) {
                            var studentRow = `<tr>
                            <td>${index + 1}</td>
                            <td>${record.student.studentName}</td>
                            <td>${record.student.studentNo}</td>
                            <td>${record.student.studentMajor}</td>
                            <td>${record.totalScore}</td>
                            <td>${record.submittedAt}</td>
                            <td><button class="btn btn-info viewSolution" data-record-id="${record.recordId}">查看答题情况</button></td> <!-- 新增查看答题情况按钮 -->
                        </tr>`;
                            studentList.append(studentRow);
                        });
                    } else {
                        studentList.append('<tr><td colspan="7">没有学生参加此试卷</td></tr>');
                    }

                    // 显示模态框
                    var studentScoreModal = new bootstrap.Modal(document.getElementById('studentScoreModal'));
                    studentScoreModal.show();
                } else {
                    alert('获取学生成绩失败');
                }
            },
            error: function() {
                alert("加载学生成绩失败！");
            }
        });
    });

    // 查看答题情况的操作
    $(document).on("click", ".viewSolution", function() {
        var recordId = $(this).data("record-id");
        fetchSolution(recordId);
    });

    // 获取学生答题情况的函数
    function fetchSolution(recordId) {
        $.ajax({
            url: '/teacher/getExamSolution',  // 获取试题解析的后端接口
            method: 'GET',
            data: { recordId: recordId },  // 传递考试记录ID
            success: function(response) {
                if (response.code === 200) {
                    var solution = response.data;  // 获取试题解析数据
                    console.log(solution);

                    // 填充解析内容
                    $('#examTitle1').text(solution.exam.title);  // 试卷标题
                    $('#teacherName').text(solution.exam.teacherName);  // 出卷人
                    $('#totalScore').text(solution.totalScore);  // 我的得分
                    $('#scorePerQuestion').text(solution.exam.scorePerQuestion);  // 填充每题分数

                    var questionsList = $('#questionsList');
                    questionsList.empty();  // 清空原有解析内容

                    // 循环遍历所有题目并显示解析
                    solution.exam.questions.forEach(function(question, index) {
                        // 判断是否正确（通过 answer.score 判断）
                        var questionClass = question.answer.score === 0 ? 'text-danger' : 'text-success';  // 错题显示红色，正确题目显示绿色
                        var studentAnswerClass = question.answer.score === 0 ? 'text-danger' : 'text-success';  // 我的答案类名
                        var questionText = `<p class="mb-2 ${questionClass}"><strong>问题 ${index + 1}：</strong> ${question.questionText}</p>`;

                        var optionsHtml = `
                        <p class="${question.answer.selectedOption === 'A' && question.answer.selectedOption !== question.correctOption ? 'text-danger' : (question.answer.selectedOption === 'A' ? 'text-success' : '')}">A. ${question.optionA}</p>
                        <p class="${question.answer.selectedOption === 'B' && question.answer.selectedOption !== question.correctOption ? 'text-danger' : (question.answer.selectedOption === 'B' ? 'text-success' : '')}">B. ${question.optionB}</p>
                        <p class="${question.answer.selectedOption === 'C' && question.answer.selectedOption !== question.correctOption ? 'text-danger' : (question.answer.selectedOption === 'C' ? 'text-success' : '')}">C. ${question.optionC}</p>
                        <p class="${question.answer.selectedOption === 'D' && question.answer.selectedOption !== question.correctOption ? 'text-danger' : (question.answer.selectedOption === 'D' ? 'text-success' : '')}">D. ${question.optionD}</p>
                    `;

                        // 错误的题目下方显示正确答案
                        var correctAnswer = `<p class="text-primary"><strong>正确答案：</strong>${question.correctOption}</p>`;

                        var questionHtml = `
                        <div class="mb-4">
                            ${questionText}
                            ${optionsHtml}
                            ${correctAnswer}
                        </div>
                    `;

                        questionsList.append(questionHtml);
                    });

                    // 显示答题情况模态框
                    var solutionModal = new bootstrap.Modal(document.getElementById('solutionModal'));
                    solutionModal.show();
                } else {
                    alert('获取试题解析失败');
                }
            },
            error: function() {
                alert('获取试题解析失败');
            }
        });
    }



    // 启动试卷
    $(document).on("click", ".startExam", function() {
        var examId = $(this).data("id");
        $.ajax({
            url: '/teacher/startExam?id=' + examId,
            type: 'PUT',
            success: function(response) {
                if(response.code === 200) {
                    loadExams();  // 重新加载试卷列表
                    alert("试卷启动成功");
                } else {
                    alert("启动失败");
                }
            },
            error: function() {
                alert("启动试卷失败！");
            }
        });
    });

    // 停止试卷
    $(document).on("click", ".stopExam", function() {
        var examId = $(this).data("id");
        $.ajax({
            url: '/teacher/stopExam?id=' + examId,
            type: 'PUT',
            success: function(response) {
                if(response.code === 200) {
                    loadExams();  // 重新加载试卷列表
                    alert("试卷停止成功");
                } else {
                    alert("停止失败");
                }
            },
            error: function() {
                alert("停止试卷失败！");
            }
        });
    });


    // 创建试卷
    $("#createExamForm").on("submit", function(e) {
        e.preventDefault();
        // 创建试卷之前，先判断一下是否表单数据合法...
        calculateTotalScore()
        var data = $(this).serialize(); // 获取表单数据

        $.ajax({
            url: '/teacher/createExam',  // 创建试卷的接口
            type: 'POST',
            data: data,
            success: function(response) {
                if(response.code === 200) {
                    loadExams();  // 重新加载试卷列表
                    // 清空一下
                    $('#examTitle').val('');
                    alert("试卷创建成功");
                } else {

                    alert(response.msg);
                }
            },
            error: function() {
                alert("创建试卷失败！");
            }
        });
    });

    // 编辑试卷
    $(document).on("click", ".editExam", function() {
        var examId = $(this).data("id");
        alert('暂时不支持编辑试卷')
        // window.location.href = "/teacher/editExam?id=" + examId;  // 导航到编辑页面
    });

    // 删除试卷
    $(document).on("click", ".deleteExam", function() {
        var examId = $(this).data("id");
        if(confirm("确定删除该试卷吗？")) {
            alert('暂时不支持删除试卷')
            // $.ajax({
            //     url: '/teacher/deleteExam?id=' + examId,
            //     type: 'DELETE',
            //     success: function(response) {
            //         if(response.code === 200) {
            //             loadExams();  // 重新加载试卷列表
            //             alert("试卷删除成功");
            //         } else {
            //             alert("删除失败");
            //         }
            //     },
            //     error: function() {
            //         alert("删除试卷失败！");
            //     }
            // });
        }
    });



    $(document).on("click", ".viewExam", function() {
        var examId = $(this).data("id");

        $.ajax({
            url: '/teacher/getExamDetails?id=' + examId,  // 请求获取试卷详情的接口
            type: 'GET',
            success: function(response) {
                if (response.code === 200) {
                    var exam = response.data;

                    // 更新试卷的基本信息
                    $('#examTitleDetail').text(exam.title);  // 试卷标题
                    $('#examCreator').text('出卷人: ' + exam.teacherName);  // 出卷人
                    $('#totalScoreOfExam').text('总分: ' + (exam.questionCount * exam.scorePerQuestion));  // 总分
                    // $('#examQuestionCount').text('题数: ' + exam.questionCount);  // 题数
                    // $('#examScorePerQuestion').text('每题分值: ' + exam.scorePerQuestion);  // 每题分值

                    // 填充试卷题目列表
                    var questionsList = $('#examQuestionsList');
                    questionsList.empty();  // 清空列表

                    exam.questions.forEach(function(question, index) {
                        var questionNumber = index + 1;  // 问题编号
                        var optionA = question.optionA;  // 选项
                        var optionB = question.optionB;  // 选项
                        var optionC = question.optionC;  // 选项
                        var optionD = question.optionD;  // 选项
                        var correctOption = question.correctOption;  // 选项

                        // 构造问题和选项
                        var questionHTML = `
                        <div class="mb-3">
                            <h5><strong>问题 ${questionNumber}: </strong>${question.questionText}</h5>
                            <div class="ms-4">
                                <p><strong>A:</strong> ${optionA}</p>
                                <p><strong>B:</strong> ${optionB}</p>
                                <p><strong>C:</strong> ${optionC}</p>
                                <p><strong>D:</strong> ${optionD}</p>
                                <p>正确答案：${correctOption}</p>
                            </div>
                        </div>
                    `;
                        questionsList.append(questionHTML);  // 添加到模态框中
                    });

                    // 显示模态框
                    var examDetailModal = new bootstrap.Modal(document.getElementById('examDetailModal'));
                    examDetailModal.show();
                } else {
                    alert('获取试卷详情失败');
                }
            },
            error: function() {
                alert("加载试卷详情失败！");
            }
        });
    });


});